/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ken
 * Date: 2023-12-26
 * Time: 17:09
 */
public class MySingleList {
    static class Node {
        public int val;
        public Node next;

        public Node(int val) {
            this.val = val;
        }
    }
        public Node head;  //代表当前链表的头结点的引用

    public void createLink() {
        Node node1 = new Node(12);
        Node node2 = new Node(22);
        Node node3 = new Node(32);
        Node node4 = new Node(42);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        head = node1;
    }
 //遍历列表
    //如果 说把整个链表 遍历完成 那么就需要head ！= null
    //如果说你遍历到链表的尾巴 head.next == null
    public void display() {
        Node cur = head;
        while (cur != null ) {
            System.out.print(cur.val+" ");
            cur = cur.next;
        }
    }
    //  查找我要找的元素是否在
    public boolean contains (int key) {
        Node cur = head;
        while (cur != null) {
            if(cur.val == key) {
                return  true;
            }
            cur = cur.next;
        }
        return false;
    }
    //当前节点数
    public int number() {
        Node cur = head;
        int count = 0;
        while (cur != null) {
            count++;
            cur = cur.next;
        }
        return count;
    }
    //头插法
    public void addFist(int data) {
        Node node = new Node(data);
        node.next = head;
        head = node;
    }
    //尾插法
    public void addLast(int data) {
        Node node = new Node(data);
        if(head == null) {
            head = node;
            return;
        }
        Node cur = head;
        while (cur.next != null) {
            cur = cur.next;
        }
        cur.next = node;
    }
    //任意位置插入，第一个数据节点为0下标
    public void addIndex(int index , int data)
            throws ListIndexoutiofException{
        checkIdex(index);
        if (index == 0) {
            addFist(data);
            return;
        }
        if (index == number()) {
            addLast(data);
            return;
        }
        Node node = finIndexSubOne(index);
        Node cur = new Node(data);
        cur.next = node.next;
        node.next = cur;
    }

    private void checkIdex (int index) {
        if(index < 0 || index > number()) {
            throw new ListIndexoutiofException("index 位置不合法");
        }
    }
    private Node finIndexSubOne(int index) {
        Node cur = head;
        int count = 0;
        while (count != index - 1) {
            cur = cur.next;
            count++;
        }
        return cur;
    }
    //清空
    public void clear() {
        head = null;
    }
}
